using System;
using System.Collections;
using System.Collections.Generic;
using Main.Dialogue;
using Main.Event;
using TMPro;
using UnityEngine;
using UnityEngine.UI;
using ZSW.Framework;
using DG.Tweening;

namespace Main.UI
{
    public class UI_Diagonal : ZSWF_InitMonoBehaviour
    {
        public GameObject dialogueBox;
        public Text dialogueText;
        public Image faceRight;
        public Image faceLeft;
        public TMP_Text nameRight;
        public TMP_Text nameLeft;
        public GameObject continueBox;

        public override void Init()
        {
            base.Init();

            MainEventSystem.ShowDialogueEvent += OnShowDialogueEvent;

            dialogueBox.SetActive(false);
        }

        private void OnShowDialogueEvent(DialoguePiece piece)
        {
            dialogueBox.SetActive(true);
            StartCoroutine(ShowDialogue(piece));
        }

        private IEnumerator ShowDialogue(DialoguePiece piece)
        {
            if (piece != null)
            {
                piece.isDone = false;

                dialogueText.text = string.Empty;
                continueBox.SetActive(false);
                faceLeft.gameObject.SetActive(false);
                faceRight.gameObject.SetActive(false);
                nameLeft.gameObject.SetActive(false);
                nameRight.gameObject.SetActive(false);

                if (!string.IsNullOrEmpty(piece.name))
                {
                    if (piece.onLeft)
                    {
                        faceLeft.gameObject.SetActive(true);
                        nameLeft.gameObject.SetActive(true);
                        nameLeft.text = piece.name;
                        faceLeft.sprite = piece.faceImage;
                    }
                    else
                    {
                        faceRight.gameObject.SetActive(true);
                        nameRight.gameObject.SetActive(true);
                        nameRight.text = piece.name;
                        faceRight.sprite = piece.faceImage;
                    }
                }
                else
                {
                    faceLeft.gameObject.SetActive(false);
                    faceRight.gameObject.SetActive(false);
                    nameLeft.gameObject.SetActive(false);
                    nameRight.gameObject.SetActive(false);
                }

                yield return dialogueText.DOText(piece.dialogueText, 1f).WaitForCompletion();

                piece.isDone = true;

                if (piece.hasToPause && piece.isDone)
                {
                    continueBox.SetActive(true);
                }
            }
            else
            {
                dialogueBox.SetActive(false);
                yield break;
            }

        }
    }
}